All files / src/components/reseller SupportTickets.tsx

0% Statements 0/110
0% Branches 0/50
0% Functions 0/21
0% Lines 0/106

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
'use client';
 
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import {
  MessageSquare,
  Clock,
  AlertCircle,
  CheckCircle,
  Plus,
  Send,
  Filter,
  SortDesc,
  RefreshCw
} from 'lucide-react';
import { ticketService, Ticket, CreateTicketRequest, TicketDetail, AddMessageRequest } from '@/services';
import TicketCard from '@/components/tickets/TicketCard';
import TicketChatDialog from '@/components/tickets/TicketChatDialog';
 
// Remove local interface since we're importing it from services
 
interface SupportTicketsProps {
  className?: string;
}
 
export default function SupportTickets({ className }: SupportTicketsProps) {
  const { t } = useTranslation('reseller');
  const [tickets, setTickets] = useState<Ticket[]>([]);
  const [loading, setLoading] = useState(true);
  const [totalUnreadCount, setTotalUnreadCount] = useState(0);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [newTicket, setNewTicket] = useState({
    title: '',
    description: '',
    priority: 'medium',
    category: 'technical'
  });
 
  // Chat modal states
  const [isChatModalOpen, setIsChatModalOpen] = useState(false);
  const [selectedTicket, setSelectedTicket] = useState<TicketDetail | null>(null);
  const [chatLoading, setChatLoading] = useState(false);
  const [newMessage, setNewMessage] = useState('');
  const [sendingMessage, setSendingMessage] = useState(false);
  const [creatingTicket, setCreatingTicket] = useState(false);
  const [error, setError] = useState<string | null>(null);
 
  // Fetch tickets and unread count using the ticket service
  useEffect(() => {
    const fetchData = async () => {
      try {
        const [ticketsResult, unreadResult] = await Promise.all([
          ticketService.getResellerTickets(),
          ticketService.getResellerUnreadCount()
        ]);
 
        if (ticketsResult.success) {
          setTickets(ticketsResult.data || []);
        } else {
          console.error('API returned error:', ticketsResult.error);
          setTickets([]);
        }
 
        if (unreadResult.success) {
          setTotalUnreadCount(unreadResult.data.total_unread);
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        setTickets([]);
      } finally {
        setLoading(false);
      }
    };
 
    fetchData();
  }, []);
 
  const handleCreateTicket = async () => {
    if (creatingTicket) return;
 
    setCreatingTicket(true);
    setError(null);
 
    try {
      const result = await ticketService.createTicket(newTicket as CreateTicketRequest);
 
      if (result.success) {
        // Add the new ticket to the list without reloading
        setTickets(prev => [result.data, ...prev]);
 
        // Reset form and close dialog
        setNewTicket({
          title: '',
          description: '',
          priority: 'medium',
          category: 'technical'
        });
        setIsCreateDialogOpen(false);
      } else {
        setError(result.error?.details || t('supportTickets.errors.createFailed'));
        console.error('Error creating ticket:', result.error);
      }
    } catch (error) {
      setError(t('supportTickets.errors.createFailedRetry'));
      console.error('Error creating ticket:', error);
    } finally {
      setCreatingTicket(false);
    }
  };
 
  // Open chat modal and load ticket details with messages
  const handleOpenChat = async (ticketId: number) => {
    setChatLoading(true);
    setIsChatModalOpen(true);
 
    try {
      const result = await ticketService.getResellerTicketMessages(ticketId);
 
      if (result.success) {
        setSelectedTicket({
          ...result.data.ticket,
          messages: result.data.messages
        });
 
        // Mark messages as read
        await ticketService.markResellerTicketMessagesRead(ticketId);
 
        // Refresh tickets list to update unread counts
        const ticketsResult = await ticketService.getResellerTickets();
        if (ticketsResult.success) {
          setTickets(ticketsResult.data || []);
        }
      } else {
        console.error('Error loading ticket details:', result.error);
      }
    } catch (error) {
      console.error('Error loading ticket details:', error);
    } finally {
      setChatLoading(false);
    }
  };
 
  // Send new message
  const handleSendMessage = async () => {
    if (!selectedTicket || !newMessage.trim() || sendingMessage) return;
 
    setSendingMessage(true);
    setError(null);
 
    try {
      const result = await ticketService.addResellerTicketMessage(selectedTicket.id, {
        message: newMessage.trim()
      } as AddMessageRequest);
 
      if (result.success) {
        // Add the new message to the chat
        setSelectedTicket(prev => prev ? {
          ...prev,
          messages: [...prev.messages, result.data]
        } : null);
 
        // Clear the input
        setNewMessage('');
 
        // Refresh tickets list to update counts
        const ticketsResult = await ticketService.getResellerTickets();
        if (ticketsResult.success) {
          setTickets(ticketsResult.data || []);
        }
      } else {
        setError(result.error?.details || t('supportTickets.errors.sendFailed'));
        console.error('Error sending message:', result.error);
      }
    } catch (error) {
      setError(t('supportTickets.errors.sendFailedRetry'));
      console.error('Error sending message:', error);
    } finally {
      setSendingMessage(false);
    }
  };
 
  // Close chat modal
  const handleCloseChat = () => {
    setIsChatModalOpen(false);
    setSelectedTicket(null);
    setNewMessage('');
  };
 
  const getTicketStats = () => {
    return {
      total: tickets.length,
      open: tickets.filter(t => t.status === 'open').length,
      in_progress: tickets.filter(t => t.status === 'in_progress').length,
      resolved: tickets.filter(t => t.status === 'resolved').length};
  };
 
  const stats = getTicketStats();
 
  if (loading) {
    return (
      <div className="space-y-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-muted rounded w-1/4"></div>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            {[...Array(4)].map((_, i) => (
              <div key={i} className="h-24 bg-muted rounded"></div>
            ))}
          </div>
          <div className="h-96 bg-muted rounded"></div>
        </div>
      </div>
    );
  }
 
  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold text-foreground">{t('supportTickets.header.title')}</h2>
          <p className="text-muted-foreground">{t('supportTickets.header.description')}</p>
          {totalUnreadCount > 0 && (
            <p className="text-sm text-destructive font-medium">
              {totalUnreadCount === 1
                ? t('supportTickets.header.unreadSingle', { count: totalUnreadCount })
                : t('supportTickets.header.unreadPlural', { count: totalUnreadCount })}
            </p>
          )}
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button className="flex items-center gap-2">
              <Plus className="h-4 w-4" />
              {t('supportTickets.header.createTicket')}
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[525px]">
            <DialogHeader>
              <DialogTitle>{t('supportTickets.createDialog.title')}</DialogTitle>
              <DialogDescription>
                {t('supportTickets.createDialog.description')}
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid gap-2">
                <Label htmlFor="title">{t('supportTickets.createDialog.titleLabel')}</Label>
                <Input
                  id="title"
                  placeholder={t('supportTickets.createDialog.titlePlaceholder')}
                  value={newTicket.title}
                  onChange={(e) => setNewTicket({...newTicket, title: e.target.value})}
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="category">{t('supportTickets.createDialog.categoryLabel')}</Label>
                <Select value={newTicket.category} onValueChange={(value) => setNewTicket({...newTicket, category: value})}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="technical">{t('supportTickets.categories.technical')}</SelectItem>
                    <SelectItem value="billing">{t('supportTickets.categories.billing')}</SelectItem>
                    <SelectItem value="account">{t('supportTickets.categories.account')}</SelectItem>
                    <SelectItem value="content">{t('supportTickets.categories.content')}</SelectItem>
                    <SelectItem value="other">{t('supportTickets.categories.other')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="priority">{t('supportTickets.createDialog.priorityLabel')}</Label>
                <Select value={newTicket.priority} onValueChange={(value) => setNewTicket({...newTicket, priority: value})}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="low">{t('supportTickets.priorities.low')}</SelectItem>
                    <SelectItem value="medium">{t('supportTickets.priorities.medium')}</SelectItem>
                    <SelectItem value="high">{t('supportTickets.priorities.high')}</SelectItem>
                    <SelectItem value="urgent">{t('supportTickets.priorities.urgent')}</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="grid gap-2">
                <Label htmlFor="description">{t('supportTickets.createDialog.descriptionLabel')}</Label>
                <Textarea
                  id="description"
                  placeholder={t('supportTickets.createDialog.descriptionPlaceholder')}
                  className="min-h-[100px]"
                  value={newTicket.description}
                  onChange={(e) => setNewTicket({...newTicket, description: e.target.value})}
                />
              </div>
            </div>
 
            {/* Error Display */}
            {error && (
              <div className="bg-destructive/10 border border-destructive/20 text-destructive px-3 py-2 rounded-md text-sm">
                {error}
              </div>
            )}
 
            <DialogFooter>
              <Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                {t('supportTickets.createDialog.cancel')}
              </Button>
              <Button
                onClick={handleCreateTicket}
                disabled={!newTicket.title || !newTicket.description || creatingTicket}
              >
                {creatingTicket ? (
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary-foreground mr-2"></div>
                ) : (
                  <Send className="h-4 w-4 mr-2" />
                )}
                {creatingTicket ? t('supportTickets.createDialog.creating') : t('supportTickets.createDialog.create')}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>
 
      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card className={className}>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('supportTickets.stats.total')}</p>
                <p className="text-2xl font-bold text-foreground">{stats.total}</p>
              </div>
              <MessageSquare className="h-8 w-8 text-primary" />
            </div>
          </CardContent>
        </Card>
 
        <Card className={className}>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('supportTickets.stats.open')}</p>
                <p className="text-2xl font-bold text-primary">{stats.open}</p>
              </div>
              <Clock className="h-8 w-8 text-primary" />
            </div>
          </CardContent>
        </Card>
 
        <Card className={className}>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('supportTickets.stats.inProgress')}</p>
                <p className="text-2xl font-bold text-yellow-600">{stats.in_progress}</p>
              </div>
              <AlertCircle className="h-8 w-8 text-yellow-600" />
            </div>
          </CardContent>
        </Card>
 
        <Card className={className}>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-muted-foreground">{t('supportTickets.stats.resolved')}</p>
                <p className="text-2xl font-bold text-green-600">{stats.resolved}</p>
              </div>
              <CheckCircle className="h-8 w-8 text-green-600" />
            </div>
          </CardContent>
        </Card>
      </div>
 
      {/* Tickets List */}
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-foreground">{t('supportTickets.list.title')}</h2>
            <p className="text-muted-foreground">
              {tickets.length === 0
                ? t('supportTickets.list.empty')
                : tickets.length === 1
                  ? t('supportTickets.list.countSingle', { count: tickets.length })
                  : t('supportTickets.list.countPlural', { count: tickets.length })}
            </p>
          </div>
          <div className="flex items-center gap-3">
            <Button variant="outline" size="sm">
              <Filter className="h-4 w-4 mr-2" />
              {t('supportTickets.list.filter')}
            </Button>
            <Button variant="outline" size="sm">
              <SortDesc className="h-4 w-4 mr-2" />
              {t('supportTickets.list.sort')}
            </Button>
            <Button variant="outline" size="sm">
              <RefreshCw className="h-4 w-4 mr-2" />
              {t('supportTickets.list.refresh')}
            </Button>
          </div>
        </div>
 
        {tickets.length === 0 ? (
          <Card className={className}>
            <CardContent className="py-16">
              <div className="text-center">
                <MessageSquare className="h-16 w-16 text-muted-foreground/50 mx-auto mb-6" />
                <h3 className="text-xl font-semibold text-foreground mb-2">{t('supportTickets.empty.title')}</h3>
                <p className="text-muted-foreground mb-6 max-w-md mx-auto">
                  {t('supportTickets.empty.description')}
                </p>
                <Button onClick={() => setIsCreateDialogOpen(true)} size="lg">
                  <Plus className="h-5 w-5 mr-2" />
                  {t('supportTickets.empty.createFirst')}
                </Button>
              </div>
            </CardContent>
          </Card>
        ) : (
          <div className="grid gap-6">
            {tickets.map((ticket) => (
              <TicketCard
                key={ticket.id}
                ticket={ticket}
                onOpenChat={handleOpenChat}
                className={className} // Assuming TicketCard accepts className, if not I need to check it
              />
            ))}
          </div>
        )}
      </div>
 
      {/* Enhanced Chat Dialog */}
      <TicketChatDialog
        isOpen={isChatModalOpen}
        onClose={handleCloseChat}
        ticket={selectedTicket}
        loading={chatLoading}
        newMessage={newMessage}
        setNewMessage={setNewMessage}
        onSendMessage={handleSendMessage}
        sendingMessage={sendingMessage}
        currentUserRole="reseller"
      />
    </div>
  );
}